package com.cy.pj.notice.dao.impl;

import com.cy.pj.notice.dao.NoticeJdbcDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Component    // 通用
@Repository // 此注解一般用于描述数据访问对象的具体实现类
public class NoticeJdbcDaoImpl implements NoticeJdbcDao {
    @Autowired
    private DataSource dataSource;




    @Override
    public int insertNotice(String sql,Object[] values) throws SQLException {
        Connection conn = dataSource.getConnection();

        PreparedStatement stmt = conn.prepareStatement(sql);
        for (int i = 0; i < values.length; i++) {
            stmt.setObject(i+1, values[i]);
        }
        stmt.execute();
        stmt.close();
        conn.close();
        return 0;
    }

    @Override
    public List<Map<String, Object>> selectNotices() throws SQLException {
        Connection conn = dataSource.getConnection();

        String sql = "select id,title,content,status,type,createdTime" +
                " from sys_notices where id>=?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, 1);
        List<Map<String, Object>> list = new ArrayList<>();
        boolean flag = pstmt.execute();
        ResultSet rs = null;
        if (flag) {
            rs = pstmt.executeQuery();
            ResultSetMetaData rsmd = pstmt.getMetaData();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String columnLabel = rsmd.getColumnLabel(i);
                    map.put(columnLabel, rs.getObject(columnLabel));
                }
                list.add(map);
            }
            list.forEach(record -> System.out.println(record));
        }
        rs.close();
        pstmt.close();
        conn.close();
        return list;
    }
}
